import { middleLogger } from '@/utils/back/devlogger';
import { redirectToLogin } from '@/utils/back/redirect';
import { pathsToRegs } from '@/utils/common';
import { NextRequest, NextResponse } from 'next/server';

const authPaths = ['/product/'];

export default function authMiddleware(req: NextRequest, next: Fn) {
  const pathname = req.nextUrl.pathname;
  const authPathRegs = pathsToRegs(authPaths);
  if (authPathRegs.some(reg => reg.test(pathname))) {
    middleLogger.info('authMiddleware', req.nextUrl.pathname);
    const token = req.cookies.get('token')?.value ?? '';
    const isApiRequest = pathname.startsWith('/api/front/');
    if (!token) {
      if (isApiRequest) {
        return new NextResponse(
          JSON.stringify({
            success: false,
            message: 'Unauthorized',
            data: { token },
          }),
          {
            status: 401,
          }
        );
      } else {
        return redirectToLogin(req.url);
      }
    }
  }

  return next(req);
}
